<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Answer;
use App\Models\Config;
use App\Models\Data;
use App\Models\Member;
use App\Models\MemberAnswer;
use App\Models\Notice;
use App\Models\Organization;
use App\Models\OrganizationSubject;
use App\Models\OrganizationSubjectNum;
use App\Models\Problem;
use App\Models\Question;
use App\Models\QuestionMember;
use App\Models\Subject;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SubjectController extends BaseController {

    /**
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
        $build = Question::query();
        if (isset($params['status'])){
            $build->where('status', $params['status']);
        }

        $build->orderBy('num', 'desc')->orderBy('created_at', 'desc');
        $pageSize = $request->input('pageSize', 50);

        $data = $build->paginate($pageSize);
        return $this->success($data);
    }


    public function create(Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        if (!isset($params['notice_title']) && empty($params['notice_title'])){
            return $this->errorCode('10001', [], '请填写标题');
        }
        if (!isset($params['content']) && empty($params['content'])){
            return $this->errorCode('10001', [], '请填写内容');
        }
        $result = Notice::query()->create(['notice_title' => $params['notice_title'], 'content' => $params['content']]);

        return $this->success($result, '添加成功');

    }

    public function destroy($id, Request $request)
    {
        $question = Notice::query()->where('notice_id', $id)->first();

        if (!$question){
            return $this->errorCode('10001', [], '公告不存在');
        }

        try {
            $result = $question->delete();
        } catch (\Exception $e) {
            return $this->errorCode('10001', [], '删除失败');
        }
        return $this->success($result, '删除成功');

    }


    public function update($id, Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Notice::query()->where('notice_id', $id)->first();
        if (!$data){
            return $this->errorCode('10001', [], '公告不存在');
        }

        if (!isset($params['notice_title']) && empty($params['notice_title'])){
            return $this->errorCode('10001', [], '请填写标题');
        }
        if (!isset($params['content']) && empty($params['content'])){
            return $this->errorCode('10001', [], '请填写内容');
        }
        $result = Notice::query()->where('notice_id', $id)->update([
            'notice_title' => $params['notice_title'],
            'content' => $params['content']
        ]);
        return $this->success($result, '修改成功');
    }


    /**组织架构绑定
     * @return array
     */
    public function addOrganizationSubject(Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        if (!isset($params['organization_id']) && empty($params['organization_id'])){
            return $this->errorCode('10001', [], '请填写部门');
        }
//        if (!isset($params['subject_id']) && empty($params['subject_id'])){
//            return $this->errorCode('10001', [], '请填写题库信息');
//        }
        $result = [];
        if (empty($params['subject_id'])){
            //绑定为空的
            OrganizationSubject::query()->where('organization_id', $params['organization_id'])->delete();
            OrganizationSubjectNum::query()->where('organization_id', $params['organization_id'])->delete();
        }else{
            $Organization = Organization::query()->where('organization_id', $params['organization_id'])->first();
            if (!$Organization){
                return $this->errorCode('10001', [], '此部门不存在，绑定失败');
            }


            OrganizationSubject::query()->where('organization_id', $params['organization_id'])->delete();

            $result = OrganizationSubject::query()->firstOrCreate([
                'organization_id' => $params['organization_id'],
                'subject_id' => $params['subject_id'],
                'subject_name' => $params['subject_name'],
                'organization_name' => $Organization->organization_name,
            ]);

            $subArr = explode(',', $params['subject_id']);
            //删除绑定以外的进行删除
            OrganizationSubjectNum::query()->whereNotIn('subject_id', $subArr)->where('organization_id', $params['organization_id'])->delete();
            foreach ($subArr as $key => $value)
            {
                $thisSub = OrganizationSubjectNum::query()->where('subject_id', $value)->where('organization_id', $params['organization_id'])->first();
                if (!$thisSub){
                    OrganizationSubjectNum::query()->create([
                        'subject_id' => $value,
                        'organization_id' => $params['organization_id'],
                        'num' => 10,
                    ]);
                }
            }


        }

        return $this->success($result, '部门题库绑定成功');
    }

    public function organizationSubjectList(Request $request)
    {
        $pageSize = $request->input('pageSize', 50);
        $result = OrganizationSubject::query()->paginate($pageSize);;
        return $this->success($result, '部门题库绑定获取成功');
    }

    /**
     * @return array
     */
    public function getOrganizationList()
    {
        $org = Organization::query()->get();
        $Subject = Subject::query()->get();

        $result['organization'] = $org;
        $result['subject'] = $Subject;
        return $this->success($result, '信息获取成功');
    }

    /**
     * @return array
     */
    public function organizationSubjectSumList()
    {
        $org = Organization::query()->get()->toArray();
        foreach ($org as $key => $value){
            $org[$key]['sub_num'] = [];
            $thisNum = OrganizationSubjectNum::query()
                ->join('ty_subject', 'ty_subject.sid', '=', 'ty_organization_subject_num.subject_id')
                ->where('organization_id', $value['organization_id'])->get();
            $org[$key]['sub_num'] = $thisNum;
        }

        return $this->success($org, '信息获取成功');

    }

    public function updateOrganizationSubjectSum(Request $request)
    {
        $params = $request->all();
        $orgId = $params['org_id'];
        $subId = $params['sub_id'];
        $num = $params['num'];
        $result = OrganizationSubjectNum::query()->where('organization_id', $orgId)->where('subject_id', $subId)->update(['num' => $num]);
        return $this->success($result, '更改');
    }

    public function exportSubject($id, Request $request)
    {
        $params = $request->all();
        try {
            $directory = storage_path();
            $url = Config::query()->where('id', 1)->first()->toArray();

            return response()->download($url['url'], '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();die;
            throw new AppException('export_fail');
        }
    }

}